
package com.woniu.config;
import com.xxl.job.core.context.XxlJobHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;

@Service
public class DingTalkService {

    private static final String ACCESS_TOKEN = "19c5c681768675693f0c5da464968a660b0d9f1fa03e65a449c0158c2c9fd2ff";
    private static final String SECRET = "SECa222a7be39d183b8b3172ef785dc291eb958eb23919e19515893d2e2e8cbf063"; // 注意：是 SEC 开头的！

    @Autowired
    private RestTemplate restTemplate;

    /**
     * 发送 Markdown 消息（支持加签）
     */
    public void sendMarkdown(String title, String content) {
        try {
            // 1. 生成 timestamp 和 sign
            long timestamp = System.currentTimeMillis();
            String sign = generateSign(timestamp, SECRET);

            // 2. 构造带加签的 Webhook URL
            String webhookUrl = String.format(
                    "https://oapi.dingtalk.com/robot/send?access_token=%s&timestamp=%d&sign=%s",
                    ACCESS_TOKEN, timestamp, URLEncoder.encode(sign, "UTF-8")
            );

            // 3. 构建请求体
            Map<String, Object> markdown = new HashMap<>();
            markdown.put("title", title);
            markdown.put("text", content);

            Map<String, Object> requestBody = new HashMap<>();
            requestBody.put("msgtype", "markdown");
            requestBody.put("markdown", markdown);

            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);

            HttpEntity<Map<String, Object>> entity = new HttpEntity<>(requestBody, headers);

            // 4. 发送请求
            ResponseEntity<Map> response = restTemplate.postForEntity(webhookUrl, entity, Map.class);

            // 5. 检查响应
            if (response.getStatusCode() == HttpStatus.OK) {
                Map<String, Object> body = response.getBody();
                if (body != null && "0".equals(body.get("errcode"))) {
                    XxlJobHelper.log("✅ 钉钉消息发送成功: %s", body.get("errmsg"));
                } else {
                    String errMsg = body != null ? body.get("errmsg").toString() : "未知错误";
                    XxlJobHelper.log("❌ 钉钉返回错误: %s", errMsg);
                }
            } else {
                XxlJobHelper.log("❌ HTTP 请求失败: %s", response.getStatusCode());
            }

        } catch (Exception e) {
            XxlJobHelper.log("❌ 发送钉钉消息异常: %s", e.getMessage());
        }
    }

    /**
     * 生成 sign 签名
     */
    private String generateSign(long timestamp, String secret) throws Exception {
        String stringToSign = timestamp + "\n" + secret;
        Mac mac = Mac.getInstance("HmacSHA256");
        mac.init(new SecretKeySpec(secret.getBytes(StandardCharsets.UTF_8), "HmacSHA256"));
        byte[] signData = mac.doFinal(stringToSign.getBytes(StandardCharsets.UTF_8));
        return new String(Base64.getEncoder().encode(signData));
    }
}